// IM初始化
 window.JIM = new JMessage({
         // debug : true
     });
 	$.ajax({
 	url:'http://liuqingwushui.top/api/imchat.php',
 	data:{},
 	success:function(data){
 	JIM.init({
 		"appkey" : data.appkey,
 		"random_str" : data.random_str,
 		"signature" : data.signature,
 		"timestamp" : data.timestamp,
 		"flag" : 0
 	}).onSuccess(function(data) {
 		console.log('success:' + JSON.stringify(data));
		ready();
 	}).onFail(function(data) {
 		console.log('error:' + JSON.stringify(data))
 		 });
 		},
 		error:function(data){
 			mui.alert("鉴权失败");
 		}
 			});

function ready(){
	var user= localStorage.getItem("account");
	var pass= localStorage.getItem("pass");
        JIM.login({
            'username' : user,
			'password':  pass
        }).onSuccess(function(data) {
            console.log(data);
			localStorage.setItem("account", data.username);
			//新朋友
			$('#newfriend').click(function(){
				$('.addlist').css("display","block");
				//点击空白处隐藏该div
				$('.addlist').click(function(e){
				var divTop = $('.addlist ul');   // 设置目标区域
				 if(!divTop.is(e.target) && divTop.has(e.target).length === 0){
					 $('.addlist').hide();}})
					//同意按钮
				$('.agree').click(function(){
					var name=$(this).parent().find('span').text();
					var that=$(this).parent();
					 JIM.acceptFriend({
					             'target_name' : name ,
					               }).onSuccess(function(data) {
									   mui.toast("同意申请");
									   that.hide();
									   addmsg=addmsg-1;
									   $('#addmsg').html(addmsg);
									   if(addmsg==0){ $('#addmsg').remove()}
								   }).onFail(function(data) {
									   console.log(data);
									   that.hide();
									   addmsg=addmsg-1;
									   $('#addmsg').html(addmsg);
									    if(addmsg==0){ $('#addmsg').remove()}
								   });
				});
					//拒绝按钮
				$('.refuse').click(function(){
					var name=$(this).parent().find('span').text();
					var that=$(this).parent();
					  JIM.declineFriend({
					             'target_name' : name ,
					               }).onSuccess(function(data) {
									   mui.toast("拒绝申请");
									   that.hide();
									   addmsg=addmsg-1;
									   $('#addmsg').html(addmsg);
									    if(addmsg==0){ $('#addmsg').remove()}
								   }).onFail(function(data) {
									   console.log(data);
									   that.hide();
									   addmsg=addmsg-1;
									   $('#addmsg').html(addmsg);
									    if(addmsg==0){ $('#addmsg').remove()}
								   });;
				});
				
			})
			//添加好友
			$('#addfriend').click(function(){
				$('.diaog1').css("display","block");
				$('#mg-reg').click(function(){$('.diaog1').css("display","none");});
				$('#mg-sub').click(function(){
					var username=$("#mg_name").val();
					var conton=$('#mg_conton').val();
					if(username!=""){
						 JIM.addFriend({
						             'target_name' : username ,
						                     'why' : conton,
						               }).onSuccess(function(data) {
						                  mui.toast("发送成功");
										  $('.diaog1').css("display","none");   
						               }).onFail(function(data) {
						                 mui.toast(data.message); 
						               });
					}else{mui.alert("梦缘号不能为空");}
				})
			})

			//获取好友列表
			 JIM.getFriendList().onSuccess(function(fdlist) {
						console.log(fdlist);
						var coum=fdlist.friend_list.length;
						$('#friend').html(coum);
						var i=0;
						run();
						function run(){
							if(i!=fdlist.friend_list.length){var name=fdlist.friend_list[i].nickname;var username=fdlist.friend_list[i].username;var k=i;
							JIM.getResource({'media_id' : fdlist.friend_list[i].avatar,}).onSuccess(function(src) {var imgsrc=src.url;
							 $('.mui-table-view').append("<li class='mui-table-view-cell'><div class='mui-slider-right mui-disabled'><a class='mui-btn mui-btn-red' onclick=delefriend('"+k+"','"+username+"')>删除</a></div><div class='mui-slider-handle' style='bottom: .1rem;' onclick=joinroom('"+name+"','"+username+"')><a><img src='"+imgsrc+"' alt='' /><span>"+name+"</span></a></div></li>");
							 }).onFail(function(src){
						 	 $('.mui-table-view').append("<li class='mui-table-view-cell'><div class='mui-slider-right mui-disabled'><a class='mui-btn mui-btn-red' onclick=delefriend('"+k+"','"+username+"')>删除</a></div><div class='mui-slider-handle' style='bottom: .1rem;' onclick=joinroom('"+name+"','"+username+"')><a><img src='img/touxiang.png' alt='' /><span>"+name+"</span></a></div></li>");})
							if(i<fdlist.friend_list.length){i++;run();}
							else{console.log("列表渲染完成!");}
							}else{console.log("列表渲染完成!");}
						}
							})
			//消息实时监听
		   JIM.onMsgReceive(function(data) {
                data = JSON.stringify(data);
                console.log('1msg_receive:' + data);
            });
			//业务事件监听
			var addmsg=0;
            JIM.onEventNotification(function(data) {
                console.log(data);
				if(data.event_type==5){
					if($('#newfriend').has("span").length)
					{
						addmsg=addmsg+1;$('#addmsg').html(addmsg);
						var name=data.from_username;
						var coun=data.description;
						JIM.getResource({'media_id' : data.media_id,}).onSuccess(function(src) {var imgsrc=src.url;
							$('.addlist ul').append("<li><img src='"+imgsrc+"' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						}).onFail(function(src){
							$('.addlist ul').append("<li><img src='img/touxiang.png' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						});
						}
					else{
						$('#newfriend').append("<span class='mui-badge mui-badge-danger' id='addmsg'></span>");addmsg=addmsg+1;$('#addmsg').html(addmsg);
						var name=data.from_username;
						var coun=data.description;
						JIM.getResource({'media_id' : data.media_id,}).onSuccess(function(src) {var imgsrc=src.url;
							$('.addlist ul').append("<li><img src='"+imgsrc+"' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						}).onFail(function(src){
							$('.addlist ul').append("<li><img src='img/touxiang.png' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						});
						}
				}
            });
			//离线消息同步监听
			JIM.onSyncConversation(function(data) { 
                console.log( data);
            });
			//业务事件同步监听
			JIM.onSyncEvent(function(data) {
				console.log(data);
				for(var i=0;i<data.length;i++){
				if(data[i].event_type==5){
					if($('#newfriend').has("span").length)
					{
						addmsg=addmsg+1;$('#addmsg').html(addmsg);
						var name=data[i].from_username;
						var coun=data[i].description;
						JIM.getResource({'media_id' : data[i].media_id,}).onSuccess(function(src) {var imgsrc=src.url;
							$('.addlist ul').append("<li><img src='"+imgsrc+"' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						}).onFail(function(src){
							$('.addlist ul').append("<li><img src='img/touxiang.png' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						});
						}
					else{
						$('#newfriend').append("<span class='mui-badge mui-badge-danger' id='addmsg'></span>");addmsg=addmsg+1;$('#addmsg').html(addmsg);
						var name=data[i].from_username;
						var coun=data[i].description;
						JIM.getResource({'media_id' : data[i].media_id,}).onSuccess(function(src) {var imgsrc=src.url;
							$('.addlist ul').append("<li><img src='"+imgsrc+"' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						}).onFail(function(src){
							$('.addlist ul').append("<li><img src='img/touxiang.png' alt=''><div style='display: inline-block;height: 1.2rem;padding: .1rem 0;line-height: .5rem;'><span>"+name+"</span><p>"+coun+"</p></div><button type='button' class='refuse'>拒绝</button><button type='button' class='agree'>同意</button></li>");
						});
						}
				}
				}
            });
			//消息已读数变更事件实时监听
			JIM.onMsgReceiptChange(function(data){
			    console.log('onMsgReceiptChange : ' + JSON.stringify(data));
			});
			//消息已读数变更事件同步监听
			JIM.onSyncMsgReceipt(function(data){
			    console.log('onSyncMsgReceipt : ' + JSON.stringify(data));
			});
			//消息透传监听
		    JIM.onTransMsgRec(function(data){
			    console.log('onTransMsgRec : ' + JSON.stringify(data));
			});
        }).onFail(function(data) {
             mui.openWindow({url:'login.html'})
        }).onTimeout(function(data) {
            mui.openWindow({url:'login.html'})
        });
		}
		function joinroom(nickname,username){
			console.log("加入聊天室:"+username);
			window.location.href="friendroom.html?nickname="+encodeURI(nickname)+"&username="+encodeURI(username)+"";
		}
		function delefriend(num,username){
			mui.confirm('确认删除该好友吗','删除',['取消','确认'],function (e) {
				if(e.index==1){
					JIM.delFriend({
					              'target_name' : username ,
					               }).onSuccess(function(data) {
					                  mui.alert("删除成功");
									  $("#myfriend li").eq(num).remove();
					               }).onFail(function(data) {
					                     mui.alert("删除失败");
					               });
				}
			},'div')
		}